<script setup>
import { onMounted, nextTick, onActivated } from 'vue';

defineOptions({
    name: 'Advertisement'
})

const props = defineProps({
    adType: {
        type: String,
        default: 'adx', // adx, adsense
    },
    isGrid: {
        type: Boolean,
        default: false
    },
    row: {
        type: [String, Number],
        default: 2
    },
    path: String,
    id: String,
    size: {
        type: Array,
        default: () => [300, 250]
    },
    adSlot: [Number, String]
})

const style = {
    '--row': props.row
}

let slot = null
function handleLoadAdScript() {
    window.googletag = window.googletag || { cmd: [] };
    googletag.cmd.push(function () {
        slot = googletag.defineSlot(props.path, props.size, props.id).addService(googletag.pubads());
        // googletag.pubads().enableSingleRequest();
        googletag.pubads().collapseEmptyDivs();
        googletag.enableServices();
    });
}

function handleRefershAd() {
    if (slot) {
        googletag.pubads().refresh([slot]);
    }
}

onMounted(() => {
    if (props.adType === 'adx') {
        handleLoadAdScript()
        nextTick(() => {
            googletag.cmd.push(function () { googletag.display(props.id); });
        })
    }

    if (props.adType === 'adsense') {
        nextTick(() => {
            (adsbygoogle = window.adsbygoogle || []).push({});
        })
    }
})

onActivated(() => {
    nextTick(() => {
        if (props.adType === 'adx') {
            handleRefershAd()
        }
    })
})
</script>

<template>
    <div class="ad" :class="{ grid: isGrid }" :style="style">
        <div class="ad-wrapper">
            <div v-if="props.adType === 'adx'" :id="props.id" :style="{ minWidth: `${props.size[0]}px`, minHeight: `${props.size[1]}px` }">
            </div>
            <ins v-if="props.adType === 'adsense'" class="adsbygoogle" style="display:block" data-ad-client="ca-pub-5249973849781057" :data-ad-slot="props.adSlot" data-ad-format="auto" data-full-width-responsive="true"></ins>
        </div>
    </div>
</template>

<style scoped lang="scss">
.ad {
    width: 100%;
    text-align: center;
    font-size: var(--s-fontsize);
    margin: 0 auto;
    color: #ffffff;

    &-wrapper {
        width: 100%;
        margin: 0 auto;

        &>div {
            display: flex;
            justify-content: center;
        }
    }

    &.grid {
        --column-count: 2;
        grid-area: var(--row) / 1 / 1 span/ var(--column-count) span;

        @media screen and (min-width: $mobile) {
            --column-count: 4;
        }

        @media screen and (min-width: $table) {
            --column-count: 5;
        }

        @media screen and (min-width: $desktop) {
            --column-count: 6;
        }
    }
}
</style>